<template>
  <div class="order-list">
    <!--路由导航面包屑-->
    <Breadcrumb></Breadcrumb>

    <div class="order-form">
      <el-form ref="orderForm" :model="orderForm" label-width="80px" size="mini">
        <el-row>
          <el-col :span="5">
             <el-form-item label="订单编号">
              <el-input v-model="orderForm.code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="开始时间">
               <el-date-picker type="date" placeholder="开始时间" v-model="orderForm.startDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
           <el-col :span="5">
            <el-form-item label="结束时间">
               <el-date-picker type="date" placeholder="结束时间" v-model="orderForm.endDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8"></el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
             <el-form-item label="下单人">
              <el-input v-model="orderForm.ordername"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="所属单位">
              <el-input v-model="orderForm.company"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5" class="line">
             <el-form-item label="汇总状态">
               <el-select v-model="orderForm.huizongStatus" placeholder="状态选择">
                <el-option label="区域一" value="shanghai"></el-option>
                <el-option label="区域二" value="beijing"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="9"><el-button type="primary" plain size="mini"  icon="el-icon-search" style="margin-left: 370px;">查询</el-button></el-col>
        </el-row>
      </el-form>
    </div>
    <div class="order-btn">
      <el-button type="primary" plain size="mini" @click="orderCollect($event)" icon="el-icon-takeaway-box" style="margin: 8px;">订单汇总</el-button>
      <download-excel style="display:inline-block;margin-left: 5px;"
          :data = "exportData"
          :fields = "json_fields" 
          :header = "title"
          name = "首客生鲜订单列表.xls">
        <el-button type="primary" plain icon="el-icon-download" size="mini" @click="downloadExcel">导出</el-button>
      </download-excel>
    </div>
    <div class="order-list">
       <el-table
        :data="orderData"
        header-row-class-name="active-header" cell-class-name="table-center" header-cell-class-name="table-center"
        size="mini"
         @selection-change="handleSelectionChange"
        border
        style="width: 100%">
         <el-table-column
          type="selection"
          :selectable='ifSelectable' 
          width="55">
        </el-table-column>
        <el-table-column
          prop="code"
          label="订单编号"
          width="180">
           <template slot-scope="scope">
            <span @click="orderDetial(scope.row)" style="color:blue;cursor: pointer;">{{scope.row.code}}</span>
           </template>
        </el-table-column>
        <el-table-column
          prop="ordername"
          label="下单人"
          width="180">
        </el-table-column>
        <el-table-column
          prop="company"
          label="所属单位">
        </el-table-column>
         <el-table-column
          prop="phone"
          label="联系电话">
        </el-table-column>
         <el-table-column
          prop="yudingTime"
          label="预定时间">
          <template slot-scope="scope">
              <span>{{dayjs(scope.row.yudingTime).format('YYYY-MM-DD HH:mm:ss')}}</span>
          </template>
        </el-table-column>
         <el-table-column
          prop="price"
          label="订单总价值">
        </el-table-column>
         <el-table-column
          prop="huizongStatus"
          label="汇总状态">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.huizongStatus === 2">已汇总</el-tag>
              <el-tag type="info" v-else>未汇总</el-tag>
            </template>
        </el-table-column>
      </el-table>
      <pagination :pageSize="page.pageSize" :total="page.total" @CurrentPageChange="CurrentPageChange"></pagination>
      <!--抽屉展示订单详情-->
      <Drawer :drawer="drawer" :orderDetialsList="orderDetialsList" @updateDrawerStatus="updateDrawerStatus"></Drawer>
    </div>
    
    
  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb.vue'
import { orderList,collectOrders, orderDetials } from '@/api/order';  //引入订单列表接口
import Pagination from '@/components/Pagination.vue'; //引入分页组件
import dayjs from 'dayjs'; //引入日期处理库
import Drawer from '@/components/Drawer.vue' //引入抽屉组件
export default {
  name: '',
  components: {
    Breadcrumb,
    Pagination,
    Drawer
  },
  data(){
    return {
      page:{
        pageSize:5,
        total:100
      },
      orderForm:{
        name:'',
        startTime:'',
        endTime:''
      },
      orderData:[],
      currentPageNumber: 1,
      collectIds:[], //用于存储选中的需要汇总的订单ID
      drawer: false, //控制抽屉组件的显示与隐藏
      orderDetialsList:[],
      exportData:[], //用于导出数据
      json_fields:{
          "订单编号":"code",
          "下单人":"ordername",
          "所属单位":"company",
          "联系电话":"phone",
          "预定时间":"yudingTime",
          "订单总价值":"price",
          "汇总状态": "huizongStatus"
      },
      title: '首客生鲜订单列表',
    }
  },
  mounted(){
    //获取订单列表数据
    this.getOrderList()
  },
  created(){

  },
  methods:{
      orderList,
      dayjs,
      /**
       * excel表单导出字典值映射处理
       */
      downloadExcel(){
        console.log("导出订单列表数据",this.orderData);
        let arr = [...this.orderData] //深拷贝订单数据
        // this.exportData = arr.map(item => {
        //   item.yudingTime = dayjs(item.yudingTime).format('YYYY-MM-DD HH:mm:ss'); //格式化日期
        //   item.huizongStatus = item.huizongStatus === 2 ? '已汇总' : '未汇总'; //转换汇总状态
        // });
        arr.forEach(item =>{
          item.yudingTime = dayjs(item.yudingTime).format('YYYY-MM-DD HH:mm:ss'); //格式化日期
          item.huizongStatus = item.huizongStatus === 2 ? '已汇总' : '未汇总'; //转换汇总状态
        })
        this.exportData= arr;
        //  this.json_fields = {
         
        // };
      },
      updateDrawerStatus(driwerStatus){
        this.drawer = driwerStatus; //更新抽屉状态
      },
      //订单详情页
      orderDetial(row){
        console.log("订单详情页被点击",row);
        this.drawer = true; //打开抽屉
        //查询订单详细数据
        orderDetials().then(response=>{
           console.log(response)
           console.log(response.data.result.list)
           this.orderDetialsList = response.data.result.list
        }).catch(error=>{
           console.log("订单详细列表接口异常",error);
        })

      },
      //是否可以选中状态的逻辑处理，业务背景：已经汇总的订单不能再次被汇总，需要将单选按钮置灰 2-已汇总 1-未汇总
      ifSelectable(row,index){
        console.log("获取选中的行row和index",row,index)
        if(row.huizongStatus === 2){
          return false; //如果订单已经汇总，则不能选中
        }
        return true; //如果订单未汇总，则可以选中
      },
      handleSelectionChange(ids) {
        console.log("选中未汇总的数据",ids);
        let arr =[];
        ids.forEach(element=>{
          arr.push(element.id)  //将选中的订单ID存入数组
        })
        this.collectIds = arr; //将选中的订单ID数组赋值给data中的collectIds
        console.log("需要汇总的订单ID数组",this.collectIds);
      },
      CurrentPageChange(currentPage){
        console.log("当前选中的页码",currentPage);
        let page = currentPage
        //this.currentPageNumber = currentPage
        //查询当前页码得到数据渲染
        this.getOrderList(page)
        // console.log("分页查询订单列表数据",response.data);
        // if(response.data.status === 200){
        //   this.orderData = response.data.data
        //   this.page.pageSize = response.data.pageSize //设置页大小
        // }else{
        //   console.log("获取订单列表失败，请稍后再试");
        //   this.orderData = []
        //   this.page.pageSize = 0
        //   this.page.total = 1;
        // }

      },
      /**
       * 获取订单详细数据
       */
      getOrderDetial(){

      },
      //在组件挂载时加载当前页数参数page不传递，默认查询第一页，如果传递就查询当前页的数据
      getOrderList(page){
        orderList({page}).then(response=>{
          console.log("订单列表数据",response.data);
          if(response.data.status === 200){
             this.orderData = response.data.data
             this.page.total = response.data.total  //设置总数据条数
             this.page.pageSize = response.data.pageSize //设置页大小
          }else{
            this.$message.error("获取订单列表失败，请稍后再试");
            this.orderData = []
            this.page.pageSize = 0
            this.page.total = 1;
          }
          
        }).catch(error=>{
          console.log("订单列表接口异常",error);
        })
      },
      //订单汇总接口,修改订单选择按钮为不可用
      setCollectOrders(){
          let ids = this.collectIds.join(",") //将数组转换为字符串
          collectOrders({ids}).then(response=>{
            console.log("订单汇总接口请求数据",ids);
            console.log("订单汇总接口返回数据",response.data);
            if(response.data.status === 200){
              this.$message.success("订单汇总成功")
              //汇总成功后需要重新加载订单列表
              this.getOrderList(this.currentPageNumber)
            }else{
              this.$message.error("订单汇总失败，请稍后再试")
            }
          }).catch(error=>{
            console.log("订单汇总接口异常",error);
            this.$message.error("订单汇总接口异常，请稍后再试")
          })
      },
      //触发汇总订单按钮
      orderCollect(event){
        console.log("汇总订单按钮被点击",event);
        if(this.collectIds.length > 1){
          this.$confirm('温馨提示，确认是否需要提交所选的内容', '汇总确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            //这里可以执行提交汇总的逻辑
            this.setCollectOrders();
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '放弃提交汇总'
            });          
          });
        }else{
          this.$message({
            type: 'warning',
            message: '请至少选择两条未汇总的订单进行汇总'
          });
        }
      }
  }
}
</script>
<style lang="less" scoped>
/*@import url(); 引入公共css类*/
.order-form{
  background-color: #eee;
}
.order-btn{
  margin-top: 10px;
  border:1px solid #eee;
}
.order-list{
      background-color: #fff;
      /deep/ .active-header{
        color: #333;
      }
      /deep/ .table-center{
        text-align: center;
      }
  }
</style>
